package com.activity;
/**
 * Created by ASUS on 2017/1/16.
 */
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.myprojectoffeixue.AESUtil;
import com.example.myprojectoffeixue.GateWay;
import com.example.myprojectoffeixue.LoginActivity;
import com.example.myprojectoffeixue.MainActivity;
import com.example.myprojectoffeixue.MyApplication;
import com.example.myprojectoffeixue.ShanPingActivity;
import com.example.myprojectoffeixue.ToastUtils;
import com.example.myprojectoffeixue.UserClass;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.localization.Gateway;
import com.localization.GlobalValue;
import com.localization.SocketUdpClient;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class WifiReceiver extends BroadcastReceiver{
    byte cmd[] = {(byte) 0xfc,0x00,0x0b,0x00,0x01,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,0x01,(byte)0xff,0x01,(byte)0xf5};
    MyApplication m;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)){
            //signal strength changed

        }else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
            //wifi连接上与否

            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if(info.getState().equals(NetworkInfo.State.DISCONNECTED)){
                System.out.println("wifi网络连接断开");
            }else if(info.getState().equals(NetworkInfo.State.CONNECTED)){

                WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                //获取当前wifi名称
                System.out.println("连接到网络--" + wifiInfo.getSSID());
                if("<unknown ssid>".equals(wifiInfo.getSSID())){
                    return;
                }else{
                    reconnect(context);
                }

                //reconnect();


               // WifiConfigActivity wf= (WifiConfigActivity) context;
                //wf.mTvApSsid.setText(wf.mWifiAdmin.getWifiConnectedSsid());
            }

        }else if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){
            //wifi打开与否
            int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);

            if(wifistate == WifiManager.WIFI_STATE_DISABLED){
                System.out.println("系统关闭wifi");
            }
            else if(wifistate == WifiManager.WIFI_STATE_ENABLED){
                System.out.println("系统开启wifi");



            }
        }


    }


    public void reconnect(Context context) {
        if (!ShanPingActivity.reconnect) {
             m= (MyApplication) context.getApplicationContext();
            GlobalValue.tcpclient = null;
            if (MyApplication.udp != null) {
                MyApplication.udp.close();
            }
            for (int i = 0; i < GlobalValue.mGateway.msocket.size(); i++) {
                GlobalValue.mGateway.close();
            }
            if(GlobalValue.mGateway!=null){
                Log.d("清空数据","清空");
                GlobalValue.mGateway.objectlist.clear();
                GlobalValue.mGateway.msocket.clear();
                GlobalValue.mGateway.MacSocke.clear();}

            info();
        }
    }

    public void info(){
        GetDeviceList();
        Gateway gateway;
        System.out.println("Hello World!");
        gateway = new Gateway();
        MyApplication.udp = new SocketUdpClient(gateway);
        MyApplication.udp.connect("","255.255.255.255",8200);
        gateway.working();
        GlobalValue.mGateway = gateway;
       runner.start();
    }


    public void GetDeviceList() {

        Log.d("我走近来了","走进来了");

        if (m.username != null) {
            Log.d("hahah","执行了");
            GateWay Gw = new GateWay();
            Gw.userId = m.userId;
            Gw.status = 1;
            String j = JSON.toJSONString(Gw);
            j = AESUtil.encrypt(j);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setHeader("Content-Type", "application/json");
            try {
                params.setBodyEntity(new StringEntity(j, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/getDeviceList", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            MyApplication.localflag=true;

                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            if (arg0.result != null && !("".equals(arg0.result))) {
                                arg0.result = AESUtil.decrypt(arg0.result);
                                Log.d("arg0", arg0.result);
                                JSONObject jb = JSONObject.parseObject(arg0.result);
                                String status = jb.getString("status");
                                if ("0".equals(status)) {
                                    JSONArray ja = jb.getJSONArray("deviceList");
                                    m.m_gateway = (ArrayList<GateWay>) JSON.parseArray(ja.toString(), GateWay.class);
                                    m.Get();
                                    if(m.c==null){
                                        m.connect();
                                    }
                                    MyApplication.localflag=false;
                                }
                            }
                        }

                    });

        }
    }



    Thread runner=new Thread(){
        @Override
        public void run() {
            boolean flag=true;
            while (flag){
                for(int i=0;i<2;i++){
                    if (GlobalValue.tcpclient == null) {
                        Log.d("Udp命令", "UDP发送");
                        if (MyApplication.udp!=null) {
                            MyApplication.udp.send(cmd);
                        }
                        try {
                            Thread.currentThread().sleep(500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }}
                flag=false;
                ShanPingActivity.reconnect=false;
            }
            super.run();
        }
    };



}



